<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Jobs\CrawlMjzjData;
use App\Models\MjzjReviewer;
use App\Services\MjzjCrawlerService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class MjzjCrawlerController extends Controller
{
    private MjzjCrawlerService $crawlerService;

    public function __construct(MjzjCrawlerService $crawlerService)
    {
        $this->crawlerService = $crawlerService;
    }

    /**
     * 手动触发爬取
     */
    public function crawl(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'keywords' => 'required|string|max:255',
            'market' => 'nullable|string|max:100',
            'size' => 'nullable|integer|min:1|max:100',
            'position' => 'nullable|integer|min:0',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $params = $validator->validated();
        
        try {
            $results = $this->crawlerService->searchReviewers($params);
            
            return response()->json([
                'success' => true,
                'message' => '爬取成功',
                'data' => $results,
                'count' => count($results)
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '爬取失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量爬取（异步队列）
     */
    public function crawlBatch(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'keywords' => 'required|array|min:1',
            'keywords.*' => 'required|string|max:255',
            'batch_size' => 'nullable|integer|min:1|max:100',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $params = $validator->validated();
        
        try {
            // 将任务加入队列
            CrawlMjzjData::dispatch($params);
            
            return response()->json([
                'success' => true,
                'message' => '批量爬取任务已加入队列',
                'keywords' => $params['keywords']
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '任务创建失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取爬取统计信息
     */
    public function stats(): JsonResponse
    {
        try {
            $stats = $this->crawlerService->getStats();
            
            return response()->json([
                'success' => true,
                'data' => $stats
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取统计信息失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取评论者列表
     */
    public function reviewers(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'page' => 'nullable|integer|min:1',
            'per_page' => 'nullable|integer|min:1|max:100',
            'keywords' => 'nullable|string|max:255',
            'platform' => 'nullable|string|max:100',
            'country' => 'nullable|string|max:100',
            'min_rating' => 'nullable|numeric|min:0|max:5',
            'min_reviews' => 'nullable|integer|min:0',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $query = MjzjReviewer::query();

        // 搜索过滤
        if ($request->filled('keywords')) {
            $keywords = $request->get('keywords');
            $query->where(function ($q) use ($keywords) {
                $q->where('name', 'LIKE', "%{$keywords}%")
                  ->orWhere('keywords', 'LIKE', "%{$keywords}%")
                  ->orWhere('description', 'LIKE', "%{$keywords}%");
            });
        }

        if ($request->filled('platform')) {
            $query->where('platform', $request->get('platform'));
        }

        if ($request->filled('country')) {
            $query->where('country', $request->get('country'));
        }

        if ($request->filled('min_rating')) {
            $query->where('rating', '>=', $request->get('min_rating'));
        }

        if ($request->filled('min_reviews')) {
            $query->where('review_count', '>=', $request->get('min_reviews'));
        }

        // 分页
        $perPage = $request->get('per_page', 20);
        $reviewers = $query->orderByDesc('created_at')->paginate($perPage);

        return response()->json([
            'success' => true,
            'data' => $reviewers->items(),
            'pagination' => [
                'current_page' => $reviewers->currentPage(),
                'per_page' => $reviewers->perPage(),
                'total' => $reviewers->total(),
                'last_page' => $reviewers->lastPage(),
            ]
        ]);
    }

    /**
     * 获取单个评论者详情
     */
    public function show(string $id): JsonResponse
    {
        try {
            $reviewer = MjzjReviewer::findOrFail($id);
            
            return response()->json([
                'success' => true,
                'data' => $reviewer
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '评论者不存在'
            ], 404);
        }
    }

    /**
     * 删除评论者
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            $reviewer = MjzjReviewer::findOrFail($id);
            $reviewer->delete();
            
            return response()->json([
                'success' => true,
                'message' => '删除成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '删除失败: ' . $e->getMessage()
            ], 500);
        }
    }
} 